#include "Thread.hpp"
#include "LockGuard.hpp"
#include <unistd.h>
#include <vector>

std::string GetThreadname()
{
    static int num = 1;
    char name[64];
    snprintf(name, sizeof(name), "Thread-%d", num);
    num ++;
    return (const char*)name;
}
void Print(int num)
{
    while(num --)
    {
        std::cout << "Helloworld-" << num << std::endl;
        sleep(1);
    }
}
static int ticket = 10000;

void BuyTicket(ThreadData* td)
{
    while(true)
    {
        // pthread_mutex_lock(mutex);
        LockGuard lockguard(td->_mutex);
        if(ticket > 0)
        {
            usleep(1000);
            std::cout << "getTicket:" << ticket << std::endl;
            ticket--;
            // pthread_mutex_unlock(mutex);

        }
        else
        {
            break;
        }
    };
}
int main()
{
    pthread_mutex_t Mutex;
    pthread_mutex_init(&Mutex, nullptr);


    const int num = 5;
    std::vector<Thread<ThreadData*>> threads;

    std::string name1 = GetThreadname();
    ThreadData *td1 = new ThreadData(name1, &Mutex);
    Thread<ThreadData*> thread1(name1, BuyTicket, td1);
    thread1.Start();
    thread1.Join();

    std::string name2 = GetThreadname();
    ThreadData *td2 = new ThreadData(name2, &Mutex);
    Thread<ThreadData*> thread2(name2, BuyTicket, td1);
    thread2.Start();
    thread2.Join();
    
    std::string name3 = GetThreadname();
    ThreadData *td3 = new ThreadData(name3, &Mutex);
    Thread<ThreadData*> thread3(name3, BuyTicket, td3);
    thread3.Start();
    thread3.Join();
    
    std::string name4 = GetThreadname();
    ThreadData *td4 = new ThreadData(name4, &Mutex);
    Thread<ThreadData*> thread4(name4, BuyTicket, td4);
    thread4.Start();
    thread4.Join();

    return 0;
}